<template>
  <el-card>
    <div class="search-input-group">
      <el-form :model="searchForm" :inline="true">
        <el-form-item style="padding:5px" label="商品名称">
          <el-input 
            v-model="searchForm.productName" 
            placeholder="请输入商品名称" 
            clearable
          />
        </el-form-item>
        <el-form-item style="padding:5px" label="商品状态">
          <el-select v-model="searchForm.productStatus" placeholder="请选择商品状态" style="width: 150px;" clearable>
            <el-option label="待审核" :value="0" />
            <el-option label="上架中" :value="1" />
            <el-option label="已交易" :value="2" />
            <el-option label="被封禁" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item style="padding:5px" label="商品类型">
          <el-select 
            v-model="searchForm.productType" 
            placeholder="请选择商品类型" 
            clearable
            style="width: 150px;"
          >
            <el-option
              v-for="item in prodTypeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="btn-group">
      <el-button 
        v-if="btnGroup.addb" 
        type="primary" 
        :icon="Plus"
        @click="showAddDialog"
      >
        添加
      </el-button>
      <el-button 
        v-if="btnGroup.editb" 
        type="success" 
        :icon="Edit"
        @click="showEditDialog"
        :disabled="multipleSelection.length !== 1"
      >
        修改
      </el-button>
      <el-button 
        v-if="btnGroup.deleteb" 
        type="danger" 
        :icon="Delete"
        @click="handleDelete"
        :disabled="multipleSelection.length <= 0"
      >
        删除
      </el-button>
    </div>
    
    <el-table 
      :data="dataList" 
      style="width: 100%" 
      row-key="productId"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" label="序号" width="80" show-overflow-tooltip/>
      <el-table-column prop="productNum" label="商品编号" width="150" show-overflow-tooltip/>
      <el-table-column prop="productName" label="商品名称" width="150" show-overflow-tooltip/>
      <el-table-column prop="productStatus" label="当前状态" width="100" show-overflow-tooltip>
        <template #default="scope">
          <el-tag 
            :type="getProductStatusTag(scope.row.productStatus)"
            disable-transitions
          >
            {{ getStatusText(scope.row.productStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="applicationId" label="申请人" width="100" show-overflow-tooltip/>
      <el-table-column prop="operateId" label="审核员编号" width="100" show-overflow-tooltip/>
      <el-table-column prop="auditDesc" label="审核描述" show-overflow-tooltip/>
      
      <!-- 展开行 -->
      <el-table-column type="expand">
        <template #default="props">
          <el-form label-position="left" inline class="table-expand">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="商品ID">
                  <span>{{ props.row.productId }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="商品编号">
                  <span>{{ props.row.productNum }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="破损程度">
                  <span>{{ getOldLevelText(props.row.productOld) }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="卖家编号">
                  <span>{{ props.row.sellerId }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="适用人群">
                  <span>{{ props.row.applicablePeople }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="交易地址">
                  <span>{{ props.row.productLocation }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="商品描述">
                  <span>{{ props.row.productDesc }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="商品图片">
                  <el-image
                    v-if="props.row.productImage"
                    :src="props.row.productImage"
                    style="width: 100px; height: 100px"
                    fit="cover"
                    :preview-src-list="[props.row.productImage]"
                  />
                  <span v-else>暂无图片</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      background
      @current-change="handleCurrentChange"
      class="pagination"
    />
  </el-card>
  
  <!-- 添加/修改商品的对话框 -->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="600px"
    @close="handleDialogClose"
  >
    <el-form
      :model="operateDataForm"
      :rules="operateDataFormRules"
      ref="operateDataFormRef"
      label-width="100px"
    >
      <el-form-item label="商品编号" prop="productNum" v-if="isEdit">
        <el-input 
          v-model="operateDataForm.productNum" 
          placeholder="请输入商品编号"
          disabled
        />
      </el-form-item>
      
      <el-form-item label="商品名称" prop="productName">
        <el-input 
          v-model="operateDataForm.productName" 
          placeholder="请输入商品名称"
        />
      </el-form-item>
      
      <el-form-item label="价格" prop="productPrice">
        <el-input-number 
          v-model="operateDataForm.productPrice" 
          placeholder="请输入价格"
          :precision="2"
          :step="0.1"
          controls-position="right"
        />
      </el-form-item>
      
      <el-form-item label="商品描述" prop="productDesc">
        <el-input 
          v-model="operateDataForm.productDesc" 
          type="textarea"
          placeholder="请输入商品描述"
        />
      </el-form-item>
      
      <el-form-item label="破损程度" prop="productOld">
        <el-select v-model="operateDataForm.productOld" placeholder="请选择破损程度">
          <el-option label="全新" :value="1" />
          <el-option label="九成新" :value="2" />
          <el-option label="五成新" :value="3" />
          <el-option label="三成新" :value="4" />
          <el-option label="破损" :value="5" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="商品类型" prop="productType">
        <el-select 
          v-model="operateDataForm.productType" 
          placeholder="请选择商品类型"
        >
          <el-option
            v-for="item in prodTypeList"
            :key="item.typeId"
            :label="item.typeName"
            :value="item.typeId"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="交易地址" prop="productLocation">
        <el-input 
          v-model="operateDataForm.productLocation" 
          placeholder="请输入交易地址"
        />
      </el-form-item>
      
      <el-form-item label="适用人群" prop="applicablePeople">
        <el-input 
          v-model="operateDataForm.applicablePeople" 
          placeholder="请输入适用人群"
        />
      </el-form-item>
      
      <el-form-item label="商品状态" prop="productStatus">
        <el-select v-model="operateDataForm.productStatus" placeholder="请选择商品状态">
          <el-option label="待审核" :value="0" />
          <el-option label="上架中" :value="1" />
          <el-option label="已交易" :value="2" />
          <el-option label="被封禁" :value="3" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="商品图片" prop="productImage">
        <el-input 
          v-model="operateDataForm.productImage" 
          placeholder="请输入图片URL"
        />
      </el-form-item>
      <!-- <el-form-item label="商品封面" prop="productImg">
    <el-upload
      class="avatar-uploader"
      action="/api/file/upload"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="operateDataForm.productImg" :src="operateDataForm.productImg" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <el-input 
      v-model="operateDataForm.productImg" 
      placeholder="上传商品封面图片"
      style="margin-top: 10px;"
    />
  </el-form-item>
  
  <el-form-item label="详细图片" prop="productDetailImgs">
    <el-upload
      action="/api/file/upload"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-success="handleDetailImgSuccess"
      :on-remove="handleDetailImgRemove"
      :before-upload="beforeDetailImgUpload"
      :file-list="detailImgFileList"
      :limit="4"
      :on-exceed="handleExceed"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <el-input 
      v-model="operateDataForm.productDetailImgs" 
      type="textarea"
      placeholder="详细图片URL列表，以逗号分隔"
      style="margin-top: 10px;"
      readonly
    />
  </el-form-item> -->
      
      <el-form-item label="卖家编号" prop="sellerId">
        <el-input-number
          v-model="operateDataForm.sellerId" 
          controls-position="right"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProductForm">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 商品详情对话框 -->
  <el-dialog
    title="商品详情"
    v-model="detailDialogVisible"
    width="700px"
  >
    <el-form
      :model="detailData"
      label-width="120px"
      label-position="left"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品ID:">
            <span>{{ detailData.productId }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品编号:">
            <span>{{ detailData.productNum }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品名称:">
            <span>{{ detailData.productName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价格:">
            <span>{{ detailData.productPrice }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品类型:">
            <span>{{ detailData.productType }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="破损程度:">
            <span>{{ getOldLevelText(detailData.productOld) }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品状态:">
            <span>{{ getStatusText(detailData.productStatus) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="卖家编号:">
            <span>{{ detailData.sellerId }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="24">
          <el-form-item label="适用人群:">
            <span>{{ detailData.applicablePeople }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="交易地址:">
            <span>{{ detailData.productLocation }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间:">
            <span>{{ detailData.tpCreateTime }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="更新时间:">
            <span>{{ detailData.tpUpdataTime }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="商品描述:">
        <span>{{ detailData.productDesc }}</span>
      </el-form-item>
      
      <el-form-item label="商品图片:">
        <el-image
          v-if="detailData.productImage"
          :src="detailData.productImage"
          style="width: 200px; height: 200px"
          fit="cover"
          :preview-src-list="[detailData.productImage]"
        />
        <span v-else>暂无图片</span>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
    Plus,
    Edit,
    Delete,
    Search,
    More 
} from '@element-plus/icons-vue'
import { onMounted, reactive, ref, computed } from "vue"
import { getList, getSearchList, add, edit, remove } from "@/api/admin/product"
import { getProductOldLevelText as getOldLevelText, getProductStatusText as getStatusText,getProductStatusTag } from "@/utils/DataTextMap"
import {getListWithoutPage as basePTList} from "@/api/common/base"

// 模糊查询商品信息
const searchForm = reactive({
  productName: '',
  productStatus: '',
  productType: ''
})

// 对话框相关数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const operateDataFormRef = ref(null)

// 添加或修改数据表单
const operateDataForm = reactive({
  productNum: '',
  applicablePeople: '',
  productDesc: '',
  productId: '',
  productImage: '',
  productLocation: '',
  productName: '',
  productOld: 1,
  productPrice: 0,
  productType: 0,
  sellerId: '',
  productStatus: 0,
  productDetailImgs: ''
})

// 表单验证规则
const operateDataFormRules = {
  productNum: [
    { required: true, message: '请输入商品编号', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  productPrice: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  productDesc: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ],
  productOld: [
    { required: true, message: '请选择破损程度', trigger: 'change' }
  ],
  productType: [
    { required: true, message: '请选择商品类型', trigger: 'change' }
  ],
  productLocation: [
    { required: true, message: '请输入交易地址', trigger: 'blur' }
  ],
  applicablePeople: [
    { required: true, message: '请输入适用人群', trigger: 'blur' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return isEdit.value ? '修改商品' : '添加商品'
})

// 显示添加商品对话框
const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(operateDataForm, {
    productNum: '',
    applicablePeople: '',
    productDesc: '',
    productId: '',
    productImage: '',
    productLocation: '',
    productName: '',
    productOld: 1,
    productPrice: 0,
    productType: 0,
    sellerId: '',
    productStatus: 0,
    productDetailImgs: ''
  })
}

// 显示编辑商品对话框
const showEditDialog = () => {
  isEdit.value = true
  dialogVisible.value = true
  // 填充表单数据
  Object.assign(operateDataForm, multipleSelection.value[0])
}

// 对话框关闭时的处理
const handleDialogClose = () => {
  operateDataFormRef.value.resetFields()
}

// 固定参数源 ---start---
const dataList = ref([])
const prodTypeList = ref([])
const multipleSelection = ref([])
const isSearch = ref(false)
const btnGroup = reactive({
    addb: true,
    editb: true,
    deleteb: true
})
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取商品列表数据
const getDataList = () => {
  let res = getList(pagination.currentPage)
  res.then(res=>{
    dataList.value=res.data.records
    let opeStr=res.operateStr
    if(opeStr.includes("*")||opeStr.includes("a")) btnGroup.addb=true
    if(opeStr.includes("*")||opeStr.includes("d")) btnGroup.deleteb=true
    if(opeStr.includes("*")||opeStr.includes("u")) btnGroup.editb=true
    pagination.total=res.data.total
    pagination.pageSize=res.data.size
    pagination.currentPage=res.data.current
  })

  let typeList=basePTList("/business/product/type")
  typeList.then(res=>{
    prodTypeList.value=res.data
  })
}

// 搜索商品数据
const handleSearch = () => {
  isSearch.value = true
  let res=getSearchList({...searchForm},pagination.currentPage)
  res.then(res=>{ 
    dataList.value=res.data.records
    pagination.total=res.data.total
    pagination.pageSize=res.data.size
    pagination.currentPage=res.data.current
  })
}

const handleResetSearch = () => {
  searchForm.productName = ""
  searchForm.productStatus = ""
  searchForm.productType = ""
  isSearch.value = false
  getDataList()
}

// 添加或修改数据操作提交
const submitProductForm = () => {
  console.log('添加商品:', operateDataForm)
  operateDataFormRef.value.validate(async (valid) => {
    if (valid) {
      // 创建提交数据，移除不需要的字段
      const submitData = {
        ...operateDataForm,
        productStatus: undefined
      }
      
      if (isEdit.value) {
        // 修改商品逻辑 - 移除sellerId字段，防止被修改
        delete submitData.sellerId
        await edit(submitData)
      } else {
        // 添加商品逻辑
        await add(submitData)
      }
      dialogVisible.value = false
      refreshList()
    }
  })
}

// 删除数据操作提交
const handleDelete = async () => {
  pagination.currentPage = 1
  const productIds = multipleSelection.value.map(item => item.productNum)
  await remove({list:productIds})
  refreshList()
}

const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 当前页改变时触发
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  refreshList()
}

const refreshList = () => {
  if (isSearch.value) handleSearch()
  else getDataList()
}
// --- end ---


// 添加详情对话框相关变量
const detailDialogVisible = ref(false)
const detailData = ref({
  productNum: "",
  applicablePeople: "",
  tpCreateTime: "",
  productDesc: "",
  productId: 0,
  productImage: "",
  productLocation: "",
  productName: "",
  productOld: 1,
  productPrice: 0,
  productType: 0,
  sellerId: 0,
  productStatus: 0,
  tpUpdataTime: ""
})

// 显示详情对话框的方法
const showDetailDialog = () => {
  if (multipleSelection.value.length === 1) {
    detailData.value = { ...multipleSelection.value[0] }
    detailDialogVisible.value = true
  }
}

onMounted(() => {
    getDataList()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.btn-group {
  margin-bottom: 15px;
}

.btn-group .el-button {
  margin-right: 1px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.search-input-group {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-input-group .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

.table-expand {
  margin-left: 50px;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>